<?php
namespace Hong\Webdav;

trait TraitGet
{
    /**
     * 从WebDAV服务器下载文件 (GET)
     * @param string $remotePath 远程路径
     * @param string|null $localPath 本地保存路径(为null时只返回内容)
     * @return bool|string 成功返回true或文件内容，失败抛出异常
     * @throws \RuntimeException 当下载失败时抛出异常
     */
    public function get($remotePath, $localPath = null)
    {
        $uri = $this->baseUri . ltrim($remotePath, '/');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_USERPWD, $this->user . ':' . $this->password);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        // 如果要保存到本地文件
        if ($localPath !== null) {
            $fp = fopen($localPath, 'w');
            if ($fp === false) {
                throw new \RuntimeException("Failed to open local file for writing: " . $localPath);
            }
            curl_setopt($ch, CURLOPT_FILE, $fp);
        } else {
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        }

        $response = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);

        // 关闭资源
        if (isset($fp)) {
            fclose($fp);
        }
        curl_close($ch);

        if ($response === false) {
            throw new \RuntimeException("WebDAV request failed: " . $error);
        }

        if ($statusCode >= 200 && $statusCode < 300) {
            return $localPath !== null ? true : $response;
        }

        // 如果失败，删除可能已部分下载的文件
        if ($localPath !== null && file_exists($localPath)) {
            unlink($localPath);
        }

        throw new \RuntimeException("Failed to GET file. Server responded with status: " . $statusCode);
    }
}
